// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Popconfirm, Upload, message, Button, Modal, Row, Col, Input, Divider,Icon,Select, Radio,DatePicker,Tooltip} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import { reqInform } from 'utils/notification'
// 当前组件样式
import styles from './giftRegistrationDetailStyle.less'
import Uploader from '../../../../widget/Upload'
import ListPage from 'widget/PageTmpl/ListPage'
import classnames from 'classnames/bind';
let cx = classnames.bind(styles);
const Option = Select.Option
const InputGroup = Input.Group;
const confirm = Modal.confirm;
const { TextArea } = Input;
import $ from 'jquery'
import Cookie from 'js-cookie'
import { download } from 'utils/util'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'
import moment from 'moment'; 

const FormItem = Form.Item
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */

const { RangePicker } = DatePicker

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
}
const formItemLayout2 = {
  labelCol: { span: 3 },
  wrapperCol: { span: 16 },
}
const formItemLayoutTime = {
	labelCol: { span: 5 },
	wrapperCol: { span: 19 },
};
const formItemLayout4 = {
	labelCol: { span: 4 },
	wrapperCol: { span: 20 },
}
const inlineFormItemLayout = {
	labelCol: { span: 0 },
	wrapperCol: { span: 20 },
}
const giftRegistrationDetailView = function({ dispatch, model, form}){
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  // modelObj.xxx获取model中状态机的值
  let { btnLoading, isSubmit,detail,regionList,actionType,projectList,filterInfoList} = modelObj

  const formItemLayout4 = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  }

  	//提交
	function submit() {
		validateFields((err, values) => {
			console.log('err',err)
			console.log('values',values)
			if (!err) {
				dispatch({
					type: `${namespace}/submit`,
					payload: {}
				})
			}else{
				message.warning('请检查必填项');
			}
		});
	}

	function showDeleteConfirm(id) {
		confirm({
			title: '删除确认',
			content: '您真的要删除此礼品信息吗?',
			okText: '确认',
			okType: 'primary',
			cancelText: '取消',
			onOk() {
				// debugger
			  dispatch({
				type: `${namespace}/giftDelete`,
				payload:{
				  id,
				}
			  })
			},
			onCancel() {
			  console.log('Cancel');
			},
		  });
	}

	function inputChange(value, type, index) {
		// debugger

		switch(type){
			case 'regionId':
				let regionValue = null
				regionList.forEach(item=>{
					if(item.regionId == value){
						regionValue = item
					}
				})
				detail['regionName'] = regionValue.regionName
				detail['regionId'] = value
				let data = regionList.filter(item=>{
					return item.regionId == value
				  })
				  data[0].projectList.forEach((item,index)=>{
					item.value = item.projectId
					item.label = item.projectName
					item.key = index
				  })
				detail['projectName'] = ''
				detail['projectId'] = ''
				dispatch({
					type: `${namespace}/updateStore`,
					payload: {
						detail:detail,
						projectList:data[0].projectList
					}
				})

				break;
			case 'projectId':
				let projectValue = null
				projectList.forEach(item=>{
					if(item.projectId == value){
						projectValue = item
					}
				})
				detail['projectName'] = projectValue.projectName
				detail['projectId'] = value
				break;
			case 'totalStockType':
				if(value=='1'){
					detail['totalStock'] = 1
				}
				detail[type] = value
				break;
			case 'limitCountType':
				if(value=='1'){
					detail['limitCount'] = 1
				}
				detail[type] = value
				break;
			case 'productType':
				detail.unitPrice = "";
				detail.productUsage =value==3?'1': ''
				detail.totalStockType = value==3?"0":''
				detail.usageScope = value==3?'3':''
				detail.limitCountType = value==3?'0':''
				form.resetFields("unitPrice");
			default:
				detail[type] = value
				
		}
		changeState({ detail })
		
	}
		//修改状态
	const changeState = (payload) => {
		// console.log(payload);
		dispatch({
			type: `${namespace}/updateStore`,
			payload: { ...payload }
		})
	};
	function removeImgUrl(type) {
		detail[type] = ''
		changeState({ detail })
	}
	//封面图改变时
	function updateImageModel(value, type) {
		detail[type] = value
		changeState({ detail })
	}

	//日期改变时
	function dateChange(m, s, type) {
		console.log(m, s)
		if (type == 'onlineTime') {
			changeState({
				detail: {
					...detail,
					startOnlineTime: s[0],
					endOnlineTime: s[1],
				}
			})
		} else if (type == 'offlineTime') {
			changeState({
				detail: {
					...detail,
					startOfflineTime: s[0],
					endOfflineTime: s[1],
				}
			})
		}

	}

  return (
    <div className={cx('pageLayout')}>
      <div className='public_listMain'>
        <div className={"functionButton"}>
          <Button type='primary' onClick={e => submit()} loading={btnLoading} disabled={!isSubmit || actionType=='look'}>提交</Button>
		  <Button type='default' onClick={e => showDeleteConfirm(detail.productId)} loading={btnLoading} disabled={!isSubmit || actionType=='look'}>删除</Button>
        </div>
        <Form>
			<div className="boxShadow">
            <CollapsiblePanels title={'礼品规则配置'} hideUpDownBtn={true}>
              <Row>
				    <Col span={12}>
									<FormItem
										{...formItemLayout4}
										extra="图片分辨率需为750px*560px，且文件大小在200kb以下，支持jpg，png格式。"
										label="礼品封面图"
										required={true}
									>
										<div className={cx('uploaderBox')}>
											<div className={cx('uploaderDiv')}>
												<Uploader
													disabled={actionType=='look'}
													uploadedUrls={detail.activityCoverImg}
													removeFileCbf={() => { removeImgUrl('activityCoverImg') }}
													uploadSuccessCbf={(imgUrl) => {
														updateImageModel(imgUrl, 'activityCoverImg')
													}}
													// showType={actionType == 'detail'?'4':"3"}
													showType='6'
													minCropBoxWidth={750}
													minCropBoxHeight={560}
													// unsetWidth={true}
													fileType='image'
													fileMaxSize='0.2'
													maxFiles='1'
												/>
											</div>
											<div className={cx('tipBox')}>
												<Icon type="question-circle" className={'mgr1'} style={{ color: '#08c' }} />
												<a href="javascript:void(0)" onClick={() => { changeImgModal(true, [giftDetail_demo3]) }}>封面图显示在哪里?</a>
											</div>
										</div>

									</FormItem>
					</Col>
              </Row>
			  <Row>
				  <Col span={12}>
				  <FormItem label='礼品名称'  {...formItemLayout}>
										{getFieldDecorator('name', {
											rules: [{
												required: true, whitespace: true, message: '请输入礼品名称'
											}],
											initialValue: detail.name ? detail.name + '' : undefined
										})(
											<Input placeholder='请输入礼品名称' disabled={actionType=='look'} onChange={(e) => { inputChange(e.target.value, 'name') }} />
										)}
									</FormItem>
				  </Col>
				  <Col span={12}>
				  <FormItem label='礼品类型'  {...formItemLayout}>
				  {getFieldDecorator('productType', {
											initialValue: detail.productType,
											rules: [
												{ required: true, whitespace: true, message: '请选择礼品类型',type:'number' },
											],
										})(

											<Select
												// disabled={actionType != 'add'} value={detail.parentProductId}
												disabled={actionType=='look'}
												onChange={(e) => inputChange(e, 'productType')}>
												<Option value={1}>实物券</Option>
												<Option value={2}>实物</Option>
												<Option value={3}>物业费</Option>
											</Select>

										)}
				  </FormItem>
				  </Col>
			  </Row>
			  <Row>
				  <Col span={12}>
				  <FormItem label='领取方式'  {...formItemLayout}>
										{getFieldDecorator('receiveWay', {
											rules: [{
												required: true, whitespace: true, message: '请输入领取方式'
											}],
											initialValue: detail.receiveWay ? detail.receiveWay + '' : undefined
										})(
											<Select
												disabled={actionType != 'add'}
												onChange={(e) => inputChange(e, 'receiveWay')}>
												<Option value={'2'}>快递邮寄</Option>
												<Option value={'1'}>现场领取</Option>
												<Option value={'0'}>形式不限</Option>
											</Select>

										)}
									</FormItem>
				  </Col>
				  <Col span={12}>
				  <FormItem label='适用场景' {...formItemLayout}>
				  {getFieldDecorator('productUsage', {
											initialValue: detail.productUsage,
											rules: [
												{ required: true, whitespace: true, message: '请选择适用场景'},
											],
										})(

											<Select
												// disabled={actionType != 'add'} value={detail.parentProductId}
												disabled={actionType=='look'}
												onChange={(e) => inputChange(e, 'productUsage')}>
												<Option value={'0'}>形式不限</Option>
												<Option value={'1'}>签约赠送</Option>
												<Option value={'2'}>抢券赠送</Option>
												<Option value={'3'}>活动</Option>
											</Select>

										)}
										
				  </FormItem>
				  </Col>
				  </Row>
				  <Row>
				  <Col span={12}>
				  <FormItem label='礼品单价'  {...formItemLayout}>
										{getFieldDecorator('unitPrice', {
											rules: [{
												required: detail.productType==1 || detail.productType==2, whitespace: true, message: '请输入礼品单价'
											},
											{pattern:/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,message: '请输入数字(支持2位小数)' },
											],
											initialValue: detail.unitPrice ? detail.unitPrice + '' : undefined
										})(
											<Input placeholder='请输入礼品单价' disabled={actionType=='look'} onChange={(e) => { inputChange(e.target.value, 'unitPrice') }} />
										)}
									</FormItem>
				  </Col>
				  <Col span={12}>
									<FormItem {...formItemLayout} label="上下架状态">
										
										{getFieldDecorator('shelfStatus', {
											initialValue: detail.shelfStatus,
											rules: [
												{ required: true, whitespace: true, message: '请选择上下架状态', type:"number"},
											],
										})(
											<Radio.Group disabled={actionType=='look'} onChange={(e) => inputChange(e.target.value, 'shelfStatus')}>
												<Radio value={1}>上架</Radio>
												<Radio value={0}>下架</Radio>
											</Radio.Group>
										)}
									</FormItem>
								</Col>
			  </Row>
			  <Row>
				  <Col span={10}>
				  <FormItem
										{...formItemLayoutTime}
										label="线上申请限期"
									// extra="注：同一时间，如果美的置业云首页有集团设置的弹窗广告，将只会显示集团设置的弹窗广告,生效时间最长设置时间为15天"
									>
										{getFieldDecorator('effectiveTime', {
											rules: [{ required: true, message: '请选择线上申请限期' },
											],
											initialValue: detail.startOnlineTime ? [moment(detail.startOnlineTime, 'YYYY-MM-DD HH:mm:ss'), moment(detail.endOnlineTime, 'YYYY-MM-DD HH:mm:ss')] : [],
										})(

											<RangePicker
												style={{ width: "100%" }}
												// disabled={actionType == 'detail'} 
												showTime={{
													hideDisabledOptions: true,
													defaultValue: [moment(null, 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],

												}}
												//   ranges={{ "今天后几分钟": [moment().add(5, 'm'), moment().add(15, 'd')], }}
												format="YYYY-MM-DD HH:mm:ss" disabled={actionType=='look'}  onChange={(date, dateString) => { dateChange(date, dateString, 'onlineTime') }}
												onOk={(date) => {
													if (detail.startOnlineTime > detail.startOfflineTime) {
														detail.startOnlineTime = null
														detail.endOnlineTime = null
														dispatch({
															type: 'updateStore',
															payload: {
																detail
															}
														})
														form.resetFields(['effectiveTime'])
														message.error('线下领取时间不能比线上开始时间早吗,请重新选择', () => {
														})
														return false
													}
												}}
											/>

										)}
									</FormItem>
								</Col>
								<Col span={2}><Tooltip title="说明：线上申请限期是指该礼品参与线上申请的时间段，一旦超过此时间段则该礼品自动下架"><Icon type="question-circle" className={cx('iconTip')} /></Tooltip></Col>
			  </Row>
			  <Row>
				  <Col span={10}>
				  <FormItem
										{...formItemLayoutTime}
										label="线下领取限期"
									// extra="注：同一时间，如果美的置业云首页有集团设置的弹窗广告，将只会显示集团设置的弹窗广告,生效时间最长设置时间为15天"
									>
										{getFieldDecorator('effectiveTime2', {
											rules: [{ required: true, message: '请选择线下申请限期' },
											],
											initialValue: detail.startOfflineTime ? [moment(detail.startOfflineTime, 'YYYY-MM-DD HH:mm:ss'), moment(detail.endOfflineTime, 'YYYY-MM-DD HH:mm:ss')] : [],
										})(
											<RangePicker
												// disabled={actionType == 'detail'} 
												style={{ width: "100%" }}
												showTime={{
													hideDisabledOptions: true,
													defaultValue: [moment(null, 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],

												}}
												//   ranges={{ "今天后几分钟": [moment().add(5, 'm'), moment().add(15, 'd')], }}
												format="YYYY-MM-DD HH:mm:ss" disabled={actionType=='look'} onChange={(date, dateString) => { dateChange(date, dateString, 'offlineTime') }}
												onOk={(date) => {
													if (detail.startOnlineTime > detail.startOfflineTime) {
														detail.startOfflineTime = null
														detail.endOfflineTime = null
														dispatch({
															type: 'updateStore',
															payload: {
																detail
															}
														})
														form.resetFields(['effectiveTime2'])
														message.error('线下领取时间不能比线上开始时间早吗,请重新选择', () => {
														})
														return false
													}
												}}
											/>

										)}
									</FormItem>
								</Col>
								<Col span={2}><Tooltip title="说明：线下领取限期是指客户领取礼品的时间段，若超过此时间段，已申请领取该礼品二维码失效。"><Icon type="question-circle" className={cx('iconTip')} /></Tooltip></Col>
			  </Row>
			  <Row>
			  <Col span={12}>
									<FormItem {...formItemLayout} label="库存数量">
										{getFieldDecorator('totalStockType', {
											initialValue: detail.totalStockType,
											rules: [
												{ required: true, whitespace: true, message: '请选择库存数量' },
											],
										})(
											<Radio.Group disabled={actionType=='look'} onChange={(e) => inputChange(e.target.value, 'totalStockType')}>
												<Radio value={'1'}>有数量限制</Radio>
												<Radio value={'0'}>无数量限制</Radio>
											</Radio.Group>
										)}
									</FormItem>
								</Col>
								{detail.totalStockType=='1'&&
								<Col span={12} >
									<FormItem {...formItemLayout} label="库存数">
										{getFieldDecorator('totalStock', {
											initialValue: detail.totalStock,
											rules: [
												{ required: detail.totalStockType=='1', pattern:/^[1-9]\d*$/, whitespace: true, message: '请输入大于等于1的数字'},
											],
										})(
											<Input disabled={actionType=='look'} placeholder='请输入库存数' onChange={(e) => { inputChange(e.target.value, 'totalStock') }} />
										)}
									</FormItem>
								</Col>
							}
				  </Row>
				  <Row>
			  <Col span={12}>
									<FormItem {...formItemLayout} label="每人限领数量">
										{getFieldDecorator('limitCountType', {
											initialValue: detail.limitCountType,
											rules: [
												{ required: true, whitespace: true, message: '请选择限领数量',},
											],
										})(
											<Radio.Group disabled={actionType=='look'} onChange={(e) => inputChange(e.target.value, 'limitCountType')}>
												<Radio value={'1'}>有数量限制</Radio>
												<Radio value={'0'}>无数量限制</Radio>
											</Radio.Group>
										)}
									</FormItem>
								</Col>
								{detail.limitCountType=='1'&&
								<Col span={12}>
									<FormItem {...formItemLayout} label="每人限领数">
										{getFieldDecorator('limitCount', {
											initialValue: detail.limitCount,
											rules: [
												{ required: detail.limitCountType=='1', pattern:/^[1-9]\d*$/, whitespace: true, message: '请输入大于等于1的数字'},
											],
										})(
											<Input disabled={actionType=='look'} placeholder='请输入每人限领数' onChange={(e) => { inputChange(e.target.value, 'limitCount') }} />
										)}
									</FormItem>
								</Col>
								}
				  </Row>
				  <Row>
				      <Col span={12}>
					  <FormItem {...formItemLayout} label="适用范围">
										{getFieldDecorator('usageScope', {
											initialValue: detail.usageScope,
											rules: [
												{ required: true, whitespace: true, message: '请选择适用范围',},
											],
										})(
											<Select
											    disabled={actionType != 'add' || 3==detail.productType} 
												// disabled={actionType != 'add'} value={detail.parentProductId}
												onChange={(e) => inputChange(e, 'usageScope')}>
												{filterInfoList.map((item,idx)=>{
														return <Select.Option key={idx}  value={item.value}>{item.name}</Select.Option>
													})}
												
											</Select>
										)}
									</FormItem>
					  </Col>
					  {(detail.usageScope!='3' && detail.usageScope)&&
					  <Col span={7}>
					  <FormItem {...formItemLayoutTime} label="所属区域">
					  {getFieldDecorator('regionId', {
											initialValue: detail.regionId,
											rules: [
												{
													required: (detail.usageScope=='2'|| detail.usageScope=='1'), whitespace: true, message: '请输入所属区域',
												},
											],
										})(
											<Select
													disabled={actionType != 'add'} 
													onChange={(e) => inputChange(e, 'regionId')} placeholder="请选择区域">
													{regionList.map((item,idx)=>{
														return <Select.Option key={idx}  value={item.value}>{item.label}</Select.Option>
													})}
												</Select>
										)}
					  </FormItem>
					  </Col>
					  }
					  {(detail.usageScope=='1'&& detail.usageScope)&&
					  <Col span={5}>
					  <FormItem {...inlineFormItemLayout}>
					  {getFieldDecorator('projectId', {
											initialValue: detail.projectId,
											rules: [
												{
													required: (detail.usageScope=='1'), whitespace: true, message: '请输入所属项目',
												},
											],
										})(
												<Select
													disabled={actionType != 'add'}
													onChange={(e) => inputChange(e, 'projectId')} placeholder="请选择项目">
													{projectList.map((item,idx)=>{
														return <Select.Option  key={idx} value={item.projectId}>{item.projectName}</Select.Option>
													})}
												</Select>
										)}
					  </FormItem>
					  </Col>
					  }
				  </Row>
				  <Row>
				  <Col span={12}>
				  <FormItem label='礼品详情'  {...formItemLayout4}>
										{getFieldDecorator('detail', {
											rules: [{
												required: true, whitespace: true, message: '请输入礼品详情'
											}],
											initialValue: detail.detail ? detail.detail + '' : undefined
										})(
											<TextArea rows={4} disabled={actionType=='look'} placeholder='请输入礼品详情' onChange={(e) => { inputChange(e.target.value, 'detail') }} />
										)}
									</FormItem>
				  </Col>
				  </Row>
            </CollapsiblePanels>
          </div>
        </Form>
      </div>
    </div>
  )
}

export default connect(mapStateToProps)(Form.create()(giftRegistrationDetailView))
